package com.googlecode.c4e.ui.wizards;

import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;
import org.eclipse.ui.PlatformUI;

import com.googlecode.c4e.api.Registry;
import com.googlecode.c4e.api.model.Server;
import com.googlecode.c4e.ui.views.ServersView;

public class EditServerWizard extends Wizard implements INewWizard {

	private EditServerWizardPage page;
	private ISelection selection;
	private Server server;

	/**
	 * Constructor for EditServerWizard.
	 */
	public EditServerWizard(Server server) {
		this.server = server;
	}

	/**
	 * Adding the page to the wizard.
	 */

	public void addPages() {
		page = new EditServerWizardPage(selection);
		page.setLabel(server.getLabel());
		page.setUrl(server.getUrl());
		page.setUsername(server.getUsername());
		page.setPassword(server.getPassword());
		page.setServerId(server.getId());
		addPage(page);
	}

	/**
	 * This method is called when 'Finish' button is pressed in the wizard. We
	 * will create an operation and run it using wizard as execution context.
	 */
	public boolean performFinish() {
		server.setUrl(page.getUrl());
		server.setLabel(page.getLabel());
		server.setUsername(page.getUsername());
		server.setPassword(page.getPassword());
		server.setId(page.getServerId());
		Registry.getDefault().saveServer(server);
		// TODO find an official way of doing this
		ServersView serversView = (ServersView) PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().findView(
						"com.googlecode.c4e.ui.views.ServersView");
		if (serversView != null) {
			serversView.refreshViewer();
		}
		return true;
	}

	/**
	 * We will accept the selection in the workbench to see if we can initialize
	 * from it.
	 * 
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}
}